import { Component, OnInit, ViewChild } from '@angular/core'
import { Router, ActivatedRoute } from '@angular/router' //路由引入
import { JsonApiService } from 'app/core/api/json-api.service'
import { config } from '../../shared/smartadmin.config'
import { DatePickerModule } from '../../shared/date-picker/date-picker.module'

declare var $: any
@Component({
  selector: 'sa-docking-bill',
  templateUrl: './docking-bill.component.html',
  styleUrls: ['./docking-bill.component.css']
})
export class DockingBillComponent implements OnInit {
  // 查询条件
  month: string = '' //账单月份
  projectId: string = '' //项目Id
  projectName: string = '' //项目名称
  projectList: any //项目数据
  accountId: string = '' //账户Id
  accountName: string = '' //账户名称
  accountList: any //账户数据
  status: string = '' //结算状态(0.未结算;1.未结清;2.已结清)

  // 返回结果
  tableData: any = [] // table的表单数据
  totalData: number = 0 //总数据条数

  // 树形结构
  level = 0 // 标记等级的
  tlist = [] // 最后遍历形成的平级数组
  parentId: string | number = '' // 父级的id

  constructor(private router: Router, private activatedRoute: ActivatedRoute, private jsonApiService: JsonApiService) {
    activatedRoute.queryParams.subscribe(queryParams => {
      const date = new Date()
      const year = date.getFullYear()
      let month: any = date.getMonth() + 1
      month = month < 10 ? `0${month}` : month
      this.month = year + '-' + month
    })
  }
  ngOnInit() {
    this.initDate()
    this.initCompanySelect()
    this.load()
  }

  handleTest(event) {
    let dom: any = event.target
    dom.style.color = 'red'
  }

  //   查询数据
  load() {
    let param = {
      companyId: this.projectId, //项目id
      accountId: this.accountId, //账户Id
      month: this.month,
      status: this.status, //结算状态
      billType: 2 //账户类型-必传(1.服务费；2.对接费)
    }
    let reqdata = 'data=' + JSON.stringify(param)
    this.jsonApiService.http('ChargeCorporAccount/listTree.html', reqdata).subscribe(result => {
      if (result.success) {
        if (result.data.length) {
          this.totalData = result.data.length
          // 遍历处理子节点
          this.tlist = []
          const newData = this.redirectResultData(result.data, {}, [])
          this.initTableData(newData)
          this.tableData = this.tlist
        } else {
          this.totalData = 0
          this.tableData = []
        }
      }
    })
  }

  // 递归处理表单数据
  initTableData(result) {
    for (let index = 0; index < result.length; index++) {
      const item = result[index]
      item.noShow = false
      this.tlist.push(item)
      if (!item.level) {
        // this.level = 0
        item.parentId = 0
      } else {
        // item.parentId = this.parentId
      }
      // item.level = this.level
      // 这里是个数组
      if (item.childNode && item.childNode.length > 0) {
        // this.parentId = item.id
        item.isShowChild = true
        // this.level += 1
        this.initTableData(item.childNode)
      }
    }
  }

  // 重构数据
  // 重构数据
  redirectResultData = (data: any, obj: any = {}, arr: any = []) => {
    let syArr: any = []
    data.forEach(item => {
      const currentId = item.id
      const parentId = item.parent
      obj[currentId] = item
      obj[currentId].noShow = false
      obj[currentId].parentId = parentId ? parentId : '0'
      if (!parentId) {
        // 最顶级
        obj[currentId].level = 0
        obj[currentId].isTop = true
        arr.push(obj[currentId])
      } else {
        if (obj[parentId]) {
          if (obj[parentId].isTop || obj[parentId].level) {
            obj[currentId].isShowChild = true
            // 找到父集
            obj[currentId].level = obj[parentId].level + 1
            if (obj[parentId].childNode) {
              obj[parentId].childNode.push(obj[currentId])
            } else {
              obj[parentId].childNode = [obj[currentId]]
            }
          } else {
            syArr.push(obj[currentId])
          }
        } else {
          // 找不到父集
          syArr.push(obj[currentId])
        }
      }
    })
    if (syArr.length > 0) {
      arr = this.redirectResultData(syArr, obj, arr)
    }
    return arr
  }

  // 展开单行
  openTr(parent) {
    parent.isShowChild = !parent.isShowChild
    for (let index = 0; index < this.tableData.length; index++) {
      const element = this.tableData[index]
      // 不仅id要一样  date也要一样
      if (element.parentId == parent.id) {
        // noShow 不展示 所以要和父组件的isShowChild取反
        element.noShow = !parent.isShowChild
        // 为了适配多级
        if (element.childNode && element.childNode.length > 0) {
          this.shrinkData(element.childNode, !parent.isShowChild)
        }
      }
    }
  }
  // 递归进行收缩或展开  适配多级
  shrinkData(data, state) {
    for (let idx = 0; idx < data.length; idx++) {
      const element = data[idx]
      // 只更改子集的
      if (element.level) {
        element.noShow = state
      }
      if (element.childNode && element.childNode.length != 0) {
        element.isShowChild = !state
        this.shrinkData(element.childNode, state)
      }
    }
  }

  isAllOpen: boolean = true
  btnText: string = '一键收缩'
  // 一键展开一键缩放
  oneKeyChange() {
    if (this.isAllOpen) {
      this.shrinkData(this.tableData, true)
      this.isAllOpen = false
      this.btnText = '一键展开'
    } else {
      this.shrinkData(this.tableData, false)
      this.isAllOpen = true
      this.btnText = '一键收缩'
    }
  }

  //账单明细
  billDetails(row) {
    const _time = this.month ? this.month.split('-') : ''
    let startTime = ''
    let endTime = ''
    if (_time) {
      startTime = `${_time[0]}-${_time[1]}-01 00:00:00`
      const totalDay = new Date(Number(_time[0]), Number(_time[1]), 0).getDate()
      endTime = `${_time[0]}-${_time[1]}-${totalDay} 23:59:59`
    }
    const queryParams = {
      companyId: row.id,
      companyName: row.text,
      billType: '2',
      startTime,
      endTime
    }
    this.rowDetail('/system/bill-details', queryParams)
  }
  //结算明细
  settlementDetails(row, status) {
    const _time = this.month ? this.month.split('-') : ''
    let startTime = ''
    let endTime = ''
    if (_time) {
      startTime = `${_time[0]}-${_time[1]}-01 00:00:00`
      const totalDay = new Date(Number(_time[0]), Number(_time[1]), 0).getDate()
      endTime = `${_time[0]}-${_time[1]}-${totalDay} 23:59:59`
    }
    const queryParams = {
      companyId: row.parent ? row.parent : row.id,
      companyName: row.parentName ? row.parentName : row.text,
      // factoryId: row.id ? row.id : '',
      // factoryName: row.text ? row.text : '',
      factoryId: row.parent ? row.id : '',
      factoryName: row.parent ? row.text : '',
      status,
      billType: '2',
      startTime,
      endTime
    }
    this.rowDetail('/system/billing-details', queryParams)
  }
  rowDetail(Url, row) {
    let BaseURL = window.location.protocol + '//' + window.location.hostname + ':' + window.location.port
    common.setCookie('jumpTo' + Url, JSON.stringify(row))
    window.open(BaseURL + '#' + Url)
  }

  //   选择月份函数
  initDate() {
    var that = this
    return new Promise(function (resolve, reject) {
      System.import('assets/js/datepicker/js/bootstrap-datetimepicker.min.js').then(() => {
        System.import('assets/js/datepicker/locales/bootstrap-datetimepicker.zh-CN.js').then(() => {
          $('#startTimePicker')
            .datetimepicker({
              //时间插件
              format: 'yyyy-mm',
              language: 'zh-CN',
              weekStart: 1,
              todayBtn: true,
              autoclose: 1,
              startView: 'year',
              maxView: 'decade',
              minView: 'year',
              forceParse: false,
              pickerPosition: 'bottom-left'
            })
            .on('changeDate', function (e) {
              var date = e.date
              var time = common.getTimeDay(date)
              that.month = time.substring(0, 7)
            })
          resolve(true)
        })
      })
    })
  }

  //   点击选中月份
  changeDateType() {
    this.load()
  }

  // 刷新表
  refresh() {
    this.load()
  }

  // 点击表单查询
  tableSearch() {
    this.load()
  }

  del_accountSelect() {
    var str = $("<span class='select2-selection__placeholder'>请选择</span>")
    $('#accountSelect').val('')
    this.accountName = ''
    this.accountId = ''
    $('#select2-accountSelect-container').empty()
    $('#select2-accountSelect-container').attr('title', '')
    $('#select2-accountSelect-container').prepend(str)
  }

  //select2 格式回调函数
  formatRepo(state) {
    if (!state.id) {
      return state.text
    }
    var $state = $('<span><i class="fa fa-user green"></i>&nbsp;&nbsp;' + state.text + '</span>')
    return $state
  }

  //拉取api数据
  initAcountSelect(companyName) {
    var that = this
    that.jsonApiService
      .http_obj('CorporAccount/list.html', {
        data: JSON.stringify({
          companyName
        })
      })
      .subscribe(data => {
        if (data.success) {
          var apiList = data.data
          var selectdata = []
          for (var i = 0; i < apiList.length; i++) {
            var obj = {
              id: apiList[i].id,
              text: apiList[i].accountName
            }
            selectdata[i] = obj
          }
        }
        this.initSelected(selectdata, '#accountSelect', data => {
          that.accountName = data.text
          that.accountId = data.id
        })
      })
  }

  // 初始化账户名称
  initSelected(selectdata, id, callback = null) {
    var that = this
    System.import('script-loader!select2/dist/js/select2.min.js').then(() => {
      System.import('assets/js/select2-zh-CN.js').then(() => {
        $(id).html('')
        $(id)
          .select2({
            language: 'zh-CN',
            placeholder: '请选择',
            allowClear: true,
            data: selectdata, //为Select添加数据
            templateResult: this.formatRepo
          })
          .on('select2:select', function (e) {
            var data = e.params.data
            callback && callback(data)
          })
        var option = new Option('', '', true, true)
        $(id).append(option)
      })
    })
  }

  //拉取项目名称api数据
  initCompanySelect() {
    var that = this
    that.jsonApiService
      .http_obj('CorporAccount/list.html', {
        data: JSON.stringify({
          searchKey: ''
        })
      })
      .subscribe(data => {
        if (data.success) {
          var apiList = data.data
          var selectdata = []
          for (var i = 0; i < apiList.length; i++) {
            var obj = {
              id: apiList[i].companyId,
              text: apiList[i].companyName
            }
            selectdata[i] = obj
          }
        }
        this.initSelected(selectdata, '#companySelect', data => {
          that.projectName = data.text
          that.projectId = data.id
          that.accountName = ''
          that.accountId = ''
          that.initAcountSelect(data.text)
        })
      })
  }

  del_companySelect() {
    var str = $("<span class='select2-selection__placeholder'>请选择</span>")
    $('#companySelect').val('')
    this.projectName = ''
    this.projectId = ''
    $('#select2-companySelect-container').empty()
    $('#select2-companySelect-container').attr('title', '')
    $('#select2-companySelect-container').prepend(str)
  }
}
